<?php
namespace app\common\service;

use app\admin\service\AlbumService;
use think\facade\Filesystem;
use think\facade\Request;
use app\common\AppService;

/**
 * @desc 上传
 * Class UploadService
 * @package app\service
 */
class UploadService extends AppService
{
    /**
     * @desc 相册上传
     * @param $file
     * @param $gid
     * @param $aid
     * @return array
     */
    public static function uploadAlbum($file, $gid, $aid)
    {
        // 获取上传配置
        $sysConf = ConfigService::getConf('sys_upload', 'admin');
        if (!empty($sysConf['size_limit']))
        {
            $validTextArr[] = 'fileSize:' . ($sysConf['size_limit'] * 1024 * 1024);
        }
        if (!empty($sysConf['ext']))
        {
            $validTextArr[] = 'fileExt:' . $sysConf['ext'];
        }
        $validText = implode(",", $validTextArr);

        try {
            // 上传验证
            $result = validate(['file' => [$validText]])->check(['file' => $file]);

            if ($result)
            {
                // 上传到服务器
                $path = Filesystem::disk('public')->putFile('upload', $file);
                $path = str_replace('\\','/',$path);

                // 图片绝对路径
                $picCover = Filesystem::getDiskConfig('public','url') . '/' . $path;

                $picUrl = '';   // 图片url
                if ($sysConf['type'] == 'local' || empty($sysConf['type']))
                {
                    // 本地上传
                    $picUrl = Request::domain() . $picCover;
                } else {
                    // 云上传
                    $ossResult = event('OssUpload', ['path' => $picCover]);
                    foreach ($ossResult as $rt)
                    {
                        if ($rt['code'] == 0 && !empty($rt['data']))
                        {
                            $picUrl = $rt['data']['path'];
                        }
                    }
                }

                // 保存图片
                $fileName = mb_substr($file->getOriginalName(), 0, 20); // 获取图片名称
                $data = [
                    'aid' => $aid,
                    'groupid' => $gid,
                    'name' => $fileName,
                    'pic' => $picUrl,
                ];
                AlbumService::addOne($data);
                return $data;
            } else {
                return self::error();
            }
        } catch (\Exception $e){
            return self::error(401, $e->getMessage());
        }
    }
}